package com.leetcode.studyplan.algorithm.basis;

import com.leetcode.studyplan.algorithm.basis.entity.ListNode;

import javax.swing.*;

/**
 * 删除
 */
public class L_82_RemoveDuplicatesFromSortedListII {


    public static void main(String[] args) {

        ListNode fifth = new ListNode(3);
        ListNode fourth = new ListNode(2, fifth);
        ListNode third = new ListNode(1, fourth);
        ListNode second = new ListNode(1, third);
        ListNode first = new ListNode(1, second);

        L_82_RemoveDuplicatesFromSortedListII duplicates = new L_82_RemoveDuplicatesFromSortedListII();
        ListNode node = duplicates.deleteDuplicates(first);
        System.out.println(node.toString());

    }

    public ListNode deleteDuplicates(ListNode head) {

        if (head == null) {
            return head;
        }

        ListNode tmp = head;
        ListNode beforeNode = head;
        while (tmp != null && tmp.next != null) {
            ListNode next = tmp.next;

            boolean duplicate = false;
            boolean headDuplicate = false;
            while (next != null && tmp.val == next.val) {
                if (tmp == head) {
                    headDuplicate = true;
                }
                tmp.next = next.next;
                next.next = null;
                next = tmp.next;
                duplicate = true;
            }

            if (duplicate) {
                beforeNode.next = tmp.next;
                tmp = beforeNode.next;
                if (headDuplicate) {
                    head = tmp;
                    beforeNode = head;
                }
            } else {
                beforeNode = tmp;
                tmp = tmp.next;
            }

        }
        return head;
    }
}
